<script setup>
import { storeToRefs } from "pinia";
import { ref, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import useWs from "@/store/useWs.js";
const useWsStore = useWs();
import useVoice from "@/store/useVoice.js";
const useVoiceStore = useVoice();
import useChat from "@/store/useChat.js";
const useChatStore = useChat();

import recordUi from "./recordUi.vue";

const content = ref(""); //文字
const chatTypeInput = ref("1"); //聊天类型1文字 2语音
const isInterrupt = ref(false); //记录上滑是否取消了
const timeOutEvent = ref(null); //长按计时
const touchY = ref(null); //上滑记录
const safeAreaInsets = ref("");
const { recorderStatus, isPlaying } = storeToRefs(useVoiceStore);

onLoad(() => {
  // initWs();
  //底部安全距离
  uni.getSystemInfo({
    success: function (res) {
      safeAreaInsets.value = res.safeAreaInsets.bottom + "px";
    },
  });
});

//长按事件（起始）
const gtouchstart = (event) => {
  //记录按下的位置
  touchY.value = event.touches[0].pageY;
  //长按500毫秒触发长按事件
  timeOutEvent.value = setTimeout(function () {
    if (isPlaying.value) {
      useWsStore.interruptVoice();
    }
    useVoiceStore.waitReplay = false;
    useWsStore.startRecorder({ online: 1 });
  }, 500);
  return false;
};
//手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
const showDeleteButton = () => {
  clearTimeout(timeOutEvent.value); //清除定时器
  //如果是长按情况下手释放 停止录音
  recorderStatus.value = 0;
  //录音状态下上划取消了
  if (isInterrupt.value) {
    //这里告诉网关 用户取消发送了 不用再返回数据了
    isInterrupt.value = false;
    useWsStore.cancleSendVoice();
    console.log("取消录音");
  }
  setTimeout(() => {
    useWsStore.stopRecorder();
  }, 1000);
  return false;
};
//如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
const gtouchmove = (e) => {
  e.preventDefault(); // 阻止默认滚动行为
  //判断上划取消
  if (e.touches[0].pageY + 30 < touchY.value) {
    isInterrupt.value = true;
    clearTimeout(timeOutEvent.value); //清除定时器
    timeOutEvent.value = 0;
  } else {
    isInterrupt.value = false;
  }
};

// 阻止长按出现复制等菜单
const onContextMenu = (event) => {
  event.preventDefault();
};

//切换语音或者文字
const checkRecored = (t) => {
  chatTypeInput.value = t;
};

//发送消息事件
const sendMsg = () => {
  if (content.value.trim() == "") return;
  if (isPlaying.value) {
    useWsStore.interruptVoice();
  }
  setTimeout(() => {
    let data = {
      content: content.value,
      roleType: "HUMAN",
    };
    //发送给网关
    useWsStore.sendTextToAgent(content.value, () => {
      useChatStore.sendMessage(data); //缓存本地
      useChatStore.userInputText = content.value;
      useChatStore.waitReplay = true;
    });

    content.value = "";
  }, 10);
};

const onKeyup = (e) => {
  if (content.value.length) {
    sendMsg();
  }
};
</script>

<template>
  <div
    class="text"
    :style="{ paddingBottom: safeAreaInsets }"
    :class="{ 'record-ing': chatTypeInput == 2 && recorderStatus == 1 }"
  >
    <!-- 文字发送输入框 -->
    <div class="text-input-box" v-show="chatTypeInput == 1">
      <input
        rows="4"
        id="varArea"
        class="text-textarea"
        placeholder="发消息..."
        v-model="content"
        @confirm="onKeyup"
      />
      <div class="input-btns">
        <!-- 发送文字按钮 -->
        <div v-show="content" @click="sendMsg">
          <div class="send-txt-btn">
            <uni-icons color="#fff" type="arrow-up" size="20"></uni-icons>
          </div>
        </div>
        <!-- 切换语音按钮 -->
        <div v-show="content == ''" @click="checkRecored(2)">
          <uni-icons color="black" type="mic" size="28"></uni-icons>
        </div>
      </div>
    </div>
    <!-- 语音发送输入框 -->
    <div
      class="text-input-box"
      :class="{
        'record-ing-box': recorderStatus == 1 && !isInterrupt,
        'record-cancle-box': recorderStatus == 1 && isInterrupt,
      }"
      v-show="chatTypeInput == 2"
    >
      <div
        class="record-btn"
        @touchstart="gtouchstart($event)"
        @touchmove="gtouchmove($event)"
        @touchend="showDeleteButton()"
        @contextmenu.prevent="onContextMenu"
      >
        <div v-show="recorderStatus != 1">按住说话</div>

        <div
          class="record-ing-txt"
          v-show="recorderStatus == 1 && !isInterrupt"
        >
          <recordUi class="record-icon" />
          <span class="record-prompt">松手发送，上移取消</span>
          录音中...
        </div>

        <div
          class="record-cancle-txt"
          v-show="recorderStatus == 1 && isInterrupt"
        >
          <span class="record-prompt">松手取消</span>
          松手取消
        </div>
      </div>

      <!-- 切换文字按钮 -->
      <div
        class="input-btns"
        v-show="recorderStatus != 1"
        @click="checkRecored(1)"
      >
        <uni-icons color="black" type="chat" size="28"></uni-icons>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.text.record-ing {
  // padding: 150px 4% 10px 4% !important
  padding-top: 300rpx;
  background-image: linear-gradient(to top, #fff, transparent 100%) !important;
  background: none;

  // bottom: 0 !important;
  // position: relative;
  // z-index: 1;
}

.text {
  width: 92%;
  padding: 20rpx 4% 0 4%;
  position: fixed;
  bottom: 0;
  left: 0;
  height: 100rpx;
  z-index: 200;
  background: #fff;

  //录音中样式
  .record-ing-box {
    background-color: #3588fe;
    .record-ing-txt {
      color: #fff;
    }
  }
  //上滑取消录音样式
  .record-cancle-box {
    .record-cancle-txt {
      color: #fff;
      .record-prompt {
        color: #ff0000;
      }
    }

    background-color: #ff0000;
  }
  // overflow: hidden;
  .record-btn {
    -webkit-touch-callout: none !important;
    // -webkit-user-select: none;
    text-align: center;
    font-size: 32rpx;
    font-weight: 100;
    width: calc(100% - 40rpx);
    position: absolute;
    bottom: 0px;
    line-height: 100rpx;
    color: #000;
    font-weight: bold;
    .record-prompt {
      position: absolute;
      width: 100%;
      text-align: center;
      top: -80rpx;
      left: 0;
      font-size: 24rpx;
      color: #3588fe;
    }

    .record-icon {
      position: absolute;
      top: -200rpx;
      left: 50%;
      margin-left: -100rpx;
      .wave-container {
        .wave {
          background-color: #3588fe;
        }
      }
    }
  }

  .text-input-box {
    position: relative;
    height: 100rpx;
    border-radius: 20rpx;
    box-shadow: 0px 0px 58rpx #cecdcd;
    width: calc(100% - 120rpx);
    padding: 0 100rpx 0 20rpx;

    .input-btns {
      position: absolute;
      right: 20rpx;
      top: 20rpx;
      z-index: 2;
      .send-txt-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 52rpx;
        height: 52rpx;
        border-radius: 50%;
        background-color: #3588fe;
      }
    }

    .text-textarea {
      height: 100rpx;
      font-size: 28rpx;
      border: none;
      line-height: 100rpx;
      // width: calc(100% - 60px);
      // padding: 0 50px 0 10px;
      background: none;
    }
  }
}
</style>
